package com.cooper.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Util class for processing with image files.
 * @Title: ImageUtil.java<br>
 * @Date: Mar 31, 2012 6:23:52 PM<br>
 * @Copyright (c) 2012 MiXuan <br> * 
 * @since 1.0
 * @author tianlg
 */
public class ImageUtils {
	
	private static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
	
	/**
	 * Get the image format by data structure.
	 * @param srcPath
	 * @return like gif,png,jpg,bmp
	 * @throws IOException
	 * @date Mar 31, 2012 6:24:30 PM
	 * @author tianlg
	 */
	public static String getImageFormat(String inputPath) throws IOException{
		InputStream input = null;
		try {
			URL url = new URL(inputPath);
			input = url.openConnection().getInputStream();
			return getImageFormat(input);
		} catch (IOException e) {
			logger.error("Error:", e);
		} finally{
			input.close();
		}
		return null;
	}
	
	/**
	 * Get the image format by data structure.
	 * @param input for example: FileInputStream of which Image should be test.
	 * @return gif,png,jpg,bmp and so on.
	 * @throws IOException
	 * @date Mar 31, 2012 6:30:59 PM
	 * @author tianlg
	 */
	public static String getImageFormat(InputStream input) throws IOException{
		ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(input));
		Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
		if(!iter.hasNext()){
			return null;
		}
		ImageReader reader = iter.next();
		iis.close();
		return reader.getFormatName().toLowerCase();
	}
	
}
